package com.hongfasoft.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * Http请求工具类
 * 
 * @author lanp
 * @since 2014-8-24 13:30:56
 * @version v1.0.1
 */
public class HttpRequestUtil
{

	/**
	 * 编码
	 * 
	 * @param source
	 * @return
	 */
	public static String urlEncode(String source, String encode)
	{
		String result = source;
		try
		{
			result = java.net.URLEncoder.encode(source, encode);
		} catch (UnsupportedEncodingException e)
		{
			e.printStackTrace();
			return "0";
		}
		return result;
	}

	/**
	 * 发起http请求获取返回结果
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @return
	 */
	public static String httpRequest(String requestUrl)
	{
		StringBuffer buffer = new StringBuffer();
		try
		{
			URL url = new URL(requestUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();

			httpUrlConn.setDoOutput(false);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setUseCaches(false);

			httpUrlConn.setRequestMethod("GET");
			httpUrlConn.connect();

			// 将返回的输入流转换成字符串
			InputStream inputStream = httpUrlConn.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

			String str = null;
			while ((str = bufferedReader.readLine()) != null)
			{
				buffer.append(str);
			}
			bufferedReader.close();
			inputStreamReader.close();
			// 释放资源
			inputStream.close();
			inputStream = null;
			httpUrlConn.disconnect();

		} catch (Exception e)
		{
			System.out.println(e.getStackTrace());
		}
		return buffer.toString();
	}

	/**
	 * 发送http请求取得返回的输入流
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @return InputStream
	 */
	public static InputStream httpRequestIO(String requestUrl)
	{
		InputStream inputStream = null;
		try
		{
			URL url = new URL(requestUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
			httpUrlConn.setRequestProperty("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*");
			httpUrlConn.setRequestProperty("Accept-Language", "zh-cn");
			httpUrlConn.setRequestProperty("UA-CPU", "x86");
			httpUrlConn.setRequestProperty("Content-type", "text/html");
			httpUrlConn.setRequestProperty("Connection", "close"); // keep-Alive，有什么用呢，你不是在访问网站，你是在采集。嘿嘿。减轻别人的压力，也是减轻自己。
			httpUrlConn.setUseCaches(false);// 不要用cache，用了也没有什么用，因为我们不会经常对一个链接频繁访问。（针对程序）
			httpUrlConn.setConnectTimeout(6 * 1000);
			httpUrlConn.setReadTimeout(6 * 1000);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setDoOutput(true);
			
			httpUrlConn.setRequestMethod("GET");
			httpUrlConn.connect();
			// 获得返回的输入流
			inputStream = httpUrlConn.getInputStream();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return inputStream;
	}
	
	/**
	 * 
	 */
	public static String sendGet(String url, String param)
	{
		String result = "";
		BufferedReader in = null;
		try
		{
			String urlNameString = url + "?" + param;
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

			connection.setRequestProperty("Host", "wtsz.jyzq.cn");
			connection.setRequestProperty("Content-Type", "text/html;charset=UTF-8");
			connection.setRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 5.0;Windows NT;DigExt)");
			connection.setRequestProperty("Accept-Encoding", "gzip,deflate,sdch");
			connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
			connection.setRequestProperty("Accept-Languag", "zh-CN,zh;q=0.8");
			connection.setRequestProperty("Connection", "keep-alive");

			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			/*
			 * Map<String, List<String>> map = connection.getHeaderFields(); //
			 * 遍历所有的响应头字段 for (String key : map.keySet()) {
			 * System.out.println(key + "--->" + map.get(key)); }
			 */
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
			String line;
			while ((line = in.readLine()) != null)
			{
				result += line;
			}
		} catch (Exception e)
		{

			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally
		{
			try
			{
				if (in != null)
				{
					in.close();
				}
			} catch (Exception e2)
			{
				e2.printStackTrace();
			}
		}
		return result;
	}

	public static String sendPost(String strURL, String params)
	{
		try
		{
			URL url = new URL(strURL);// 创建连接
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoOutput(true);
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestMethod("POST"); // 设置请求方式
			connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
			connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式

			connection.connect();
			OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
			out.append(params);
			out.flush();
			out.close();
			// 读取响应
			int length = (int) connection.getContentLength();// 获取长度
			InputStream is = connection.getInputStream();
			if (length != -1)
			{
				byte[] data = new byte[length];
				byte[] temp = new byte[512];
				int readLen = 0;
				int destPos = 0;
				while ((readLen = is.read(temp)) > 0)
				{
					System.arraycopy(temp, 0, data, destPos, readLen);
					destPos += readLen;
				}
				String result = new String(data, "UTF-8"); // utf-8编码
				return result;
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
		return "error"; // 自定义错误信息
	}

	/**
	 * 发送http请求取得返回的输入流
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @return InputStream
	 */
	public static InputStream httpGet(String requestUrl, String param)
	{
		InputStream inputStream = null;
		try
		{
			URL url = new URL(requestUrl + "?" + param);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
			httpUrlConn
					.setRequestProperty(
							"Accept",
							"image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*");
			httpUrlConn.setRequestProperty("Accept-Language", "zh-cn");
			httpUrlConn.setRequestProperty("UA-CPU", "x86");
			httpUrlConn.setRequestProperty("Content-type", "text/html");
			httpUrlConn.setRequestProperty("Connection", "close"); // keep-Alive，有什么用呢，你不是在访问网站，你是在采集。嘿嘿。减轻别人的压力，也是减轻自己。
			httpUrlConn.setUseCaches(false);// 不要用cache，用了也没有什么用，因为我们不会经常对一个链接频繁访问。（针对程序）
			httpUrlConn.setConnectTimeout(6 * 1000);
			httpUrlConn.setReadTimeout(6 * 1000);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setDoOutput(true);

			httpUrlConn.setRequestMethod("GET");
			httpUrlConn.connect();

			// 获得返回的输入流
			inputStream = httpUrlConn.getInputStream();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return inputStream;
	}

	/**
	 * 发送http请求取得返回的输入流
	 * 
	 * @param requestUrl
	 *            请求地址
	 * @return InputStream
	 */
	public static InputStream httpPOST(String requestUrl, String param)
	{
		InputStream inputStream = null;
		try
		{
			URL url = new URL(requestUrl);
			HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
			httpUrlConn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)");
			httpUrlConn
					.setRequestProperty(
							"Accept",
							"image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*");
			httpUrlConn.setRequestProperty("Accept-Language", "zh-cn");
			httpUrlConn.setRequestProperty("UA-CPU", "x86");
			httpUrlConn.setRequestProperty("Content-type", "text/html");
			httpUrlConn.setRequestProperty("Connection", "close"); // keep-Alive，有什么用呢，你不是在访问网站，你是在采集。嘿嘿。减轻别人的压力，也是减轻自己。
			httpUrlConn.setUseCaches(false);// 不要用cache，用了也没有什么用，因为我们不会经常对一个链接频繁访问。（针对程序）
			httpUrlConn.setConnectTimeout(6 * 1000);
			httpUrlConn.setReadTimeout(6 * 1000);
			httpUrlConn.setDoInput(true);
			httpUrlConn.setDoOutput(true);

			httpUrlConn.setRequestMethod("POST");
			httpUrlConn.connect();
			OutputStreamWriter out = new OutputStreamWriter(httpUrlConn.getOutputStream(), "UTF-8"); // utf-8编码
			out.append(param);
			out.flush();
			out.close();

			// 获得返回的输入流
			inputStream = httpUrlConn.getInputStream();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return inputStream;
	}
}